﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using EasyToHelp.Business;

namespace HNHLFrameWork.Controllers
{
    public class FormManageController : Controller
    {
        #region 表单列表信息
        public IActionResult Index()
        {
            var list = FormService.GetTableFormList();
            return View(list);
        }
        #endregion

        #region 表单字段管理
        /// <summary>
        /// 表单字段管理
        /// </summary>
        /// <returns></returns>
        public IActionResult FormFieldManage(string TableName)
        {
            ViewBag.TableName = TableName;
            var list = FormService.GetTableManageFieldList(TableName);
            return View(list);
        }
        /// <summary>
        /// 同步表单字段数据
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public IActionResult synTableManageField(string TableName)
        {
            return Json(FormService.synTableManageField(TableName));
        }
        #endregion

        #region 表单生成
        /// <summary>
        /// 表单生成
        /// </summary>
        /// <returns></returns>
        public IActionResult FormView(string TableName, string PkName = "", string PkValue = "", string FkName = "", string FkValue = "")
        {
            if (string.IsNullOrWhiteSpace(TableName))
            {
                return Content("缺少参数或参数不正确！");
            }
            var list = FormService.GetTableManageFieldList(TableName).OrderBy(x => x.SortOrder).ToList();
            if (list.Count > 0)
            {
                ViewBag.BusinessName = list.FirstOrDefault().BusinessName;
            }
            else
            {
                return Content("关于该参数信息没有配置！");
            }
            StringBuilder sb = new StringBuilder();
            StringBuilder js = new StringBuilder();
            List<string> datelist = new List<string>();
            List<string> editordlist = new List<string>();
            List<string> uploadlist = new List<string>();
            List<string> checkboxlist = new List<string>();
            sb.Append("<input type=\"hidden\" id=\"TableName\" name =\"TableName\" value=\"" + TableName + "\" />\r\n");
            sb.Append("<input type=\"hidden\" id=\"PkName\" name =\"PkName\" value=\"" + PkName + "\" />\r\n");
            sb.Append("<input type=\"hidden\" id=\"PkValue\" name =\"PkValue\" value=\"" + PkValue + "\" />\r\n");
            sb.Append("<input type=\"hidden\" id=\"FkName\" name =\"FkName\" value=\"" + FkName + "\" />\r\n");
            sb.Append("<input type=\"hidden\" id=\"FkValue\" name =\"FkValue\" value=\"" + FkValue + "\" />\r\n");
            DataTable dt = FormService.GetArbitrarilyData(TableName, FkName, FkValue);
            list.ForEach(x =>
            {
                #region 隐藏域控件
                if (x.FieldType == "hidden")
                {
                    sb.Append("<input type=\"hidden\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" value=\"" + PkValue + "\" />\r\n");
                }
                #endregion
                if (x.IsSearchPkName)
                {
                    #region 单选控件
                    if (x.FieldType == "radio")
                    {
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        if (!string.IsNullOrWhiteSpace(x.SqlQuery))
                        {
                            DataTable radiodt = FormService.GetControlInfo(x.SqlQuery);
                            for (int i = 0; i < radiodt.Rows.Count; i++)
                            {
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    foreach (DataRow item in dt.Rows)
                                    {
                                        if (item[x.EnglishName.ToString()].ToString() == radiodt.Rows[i][x.VauleFieldName].ToString())
                                        {
                                            sb.Append("     <input checked=\"\" type=\"radio\" name=\"" + x.EnglishName + "\" value=\"" + radiodt.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + radiodt.Rows[i][x.TextFieldName].ToString() + "\">");
                                            sb.Append("\r\n");//每一行数据换行
                                        }
                                        else
                                        {
                                            sb.Append("     <input type=\"radio\" name=\"" + x.EnglishName + "\" value=\"" + radiodt.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + radiodt.Rows[i][x.TextFieldName].ToString() + "\">");
                                            sb.Append("\r\n");//每一行数据换行
                                        }
                                    }
                                }
                                else
                                {
                                    if (i == 0)
                                    {
                                        sb.Append("     <input checked=\"\" type=\"radio\" name=\"" + x.EnglishName + "\" value=\"" + radiodt.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + radiodt.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行
                                    }
                                    else
                                    {
                                        sb.Append("     <input type=\"radio\" name=\"" + x.EnglishName + "\" value=\"" + radiodt.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + radiodt.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行
                                    }
                                }

                            }
                        }
                        sb.Append("  </div> \r\n");
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 是否控件
                    if (x.FieldType == "bit")
                    {
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                if (item[x.EnglishName.ToString()].ToString() == "1")
                                {
                                    sb.Append("     <input checked=\"\"  type=\"radio\" name=\"" + x.EnglishName + "\" value=\"1\" title=\"是\">");
                                    sb.Append("\r\n");//每一行数据换行
                                    sb.Append("     <input type=\"radio\" name=\"" + x.EnglishName + "\" value=\"0\" title=\"否\">");
                                    sb.Append("\r\n");//每一行数据换行
                                }
                                else if (item[x.EnglishName.ToString()].ToString() == "0")
                                {
                                    sb.Append("     <input  type=\"radio\" name=\"" + x.EnglishName + "\" value=\"1\" title=\"是\">");
                                    sb.Append("\r\n");//每一行数据换行
                                    sb.Append("     <input checked=\"\" type=\"radio\" name=\"" + x.EnglishName + "\" value=\"0\" title=\"否\">");
                                    sb.Append("\r\n");//每一行数据换行
                                }
                                else
                                {
                                    sb.Append("     <input  type=\"radio\" name=\"" + x.EnglishName + "\" value=\"1\" title=\"是\">");
                                    sb.Append("\r\n");//每一行数据换行
                                    sb.Append("     <input checked=\"\" type=\"radio\" name=\"" + x.EnglishName + "\" value=\"0\" title=\"否\">");
                                    sb.Append("\r\n");//每一行数据换行
                                }
                            }
                        }
                        else
                        {
                            sb.Append("     <input  type=\"radio\" name=\"" + x.EnglishName + "\" value=\"1\" title=\"是\">");
                            sb.Append("\r\n");//每一行数据换行
                            sb.Append("     <input checked=\"\" type=\"radio\" name=\"" + x.EnglishName + "\" value=\"0\" title=\"否\">");
                            sb.Append("\r\n");//每一行数据换
                        }
                       
                        sb.Append("  </div> \r\n");
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 下拉框控件
                    if (x.FieldType == "select")
                    {
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        if (!string.IsNullOrWhiteSpace(x.SqlQuery))
                        {
                            sb.Append("<select id=" + x.EnglishName + " name=" + x.EnglishName + " lay-filter=" + x.EnglishName + ">");
                            DataTable selectdt = FormService.GetControlInfo(x.SqlQuery);
                            sb.Append("  <option value=\"\">请选择</option>");
                            foreach (DataRow row in selectdt.Rows)//获取每一行
                            {
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    foreach (DataRow item in dt.Rows)
                                    {
                                        if (item[x.EnglishName.ToString()].ToString() == row[x.VauleFieldName].ToString())
                                        {
                                            sb.Append(" <option selected  value=" + row[x.VauleFieldName] + ">" + row[x.TextFieldName] + "</option>");
                                            sb.Append("\r\n");//每一行数据换行
                                        }
                                        else
                                        {
                                            sb.Append(" <option value=" + row[x.VauleFieldName] + ">" + row[x.TextFieldName] + "</option>");
                                            sb.Append("\r\n");//每一行数据换行
                                        }

                                    }
                                }
                                else
                                {
                                    sb.Append(" <option value=" + row[x.VauleFieldName] + ">" + row[x.TextFieldName] + "</option>");
                                    sb.Append("\r\n");//每一行数据换行
                                }

                            }
                            sb.Append("</select>");
                        }
                        sb.Append("  </div> \r\n");
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 多选框控件
                    if (x.FieldType == "checkbox")
                    {
                        checkboxlist.Add(x.EnglishName.ToString());
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        if (!string.IsNullOrWhiteSpace(x.SqlQuery))
                        {
                            DataTable checkbox = FormService.GetControlInfo(x.SqlQuery);
                            string[] sArray = null;
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                sArray = dt.Rows[0][x.EnglishName.ToString()].ToString().Split(',');
                            }
                            var checkedstr = string.Empty;
                            for (int i = 0; i < checkbox.Rows.Count; i++)
                            {
                                if (sArray != null)
                                {
                                    bool exists = ((IList)sArray).Contains(checkbox.Rows[i][x.VauleFieldName].ToString());
                                    if (exists)
                                    {
                                        sb.Append("     <input checked type=\"checkbox\" name=\"" + x.EnglishName + "\" value=\"" + checkbox.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + checkbox.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行 
                                    }
                                    else
                                    {
                                        sb.Append("     <input type=\"checkbox\" name=\"" + x.EnglishName + "\" value=\"" + checkbox.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + checkbox.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行 
                                    }
                                }
                                else
                                {
                                    if (i == 0)
                                    {
                                        sb.Append("     <input checked type=\"checkbox\" name=\"" + x.EnglishName + "\" value=\"" + checkbox.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + checkbox.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行 
                                    }
                                    else
                                    {
                                        sb.Append("     <input type=\"checkbox\" name=\"" + x.EnglishName + "\" value=\"" + checkbox.Rows[i][x.VauleFieldName].ToString() + "\" title=\"" + checkbox.Rows[i][x.TextFieldName].ToString() + "\">");
                                        sb.Append("\r\n");//每一行数据换行 
                                    }
                                }
                            }
                        }
                        sb.Append("  </div> \r\n");
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 输入框控件
                    if (x.FieldType == "text")
                    {
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                if (string.IsNullOrWhiteSpace(item[x.EnglishName.ToString()].ToString()))
                                {
                                    sb.Append("    <input value=\"\" type=\"text\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" required lay-verify=\"required\" placeholder=\"" + x.Msg + "\" autocomplete=\"off\" class=\"layui-input\"> \r\n");
                                }
                                else
                                {
                                    sb.Append("    <input value=" + item[x.EnglishName.ToString()].ToString() + " type=\"text\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" required lay-verify=\"required\" placeholder=\"" + x.Msg + "\" autocomplete=\"off\" class=\"layui-input\"> \r\n");
                                }
                            }
                        }
                        else
                        {
                            sb.Append("    <input value=\"\" type=\"text\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" required lay-verify=\"required\" placeholder=\"" + x.Msg + "\" autocomplete=\"off\" class=\"layui-input\"> \r\n");
                        }
                        sb.Append("  </div> \r\n");
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 图片上传控件
                    if (x.FieldType == "upload")
                    {
                        uploadlist.Add(x.EnglishName.ToString());
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("  <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("  <div class=\"layui-input-block\"> \r\n");
                        sb.Append("    <div class=\"layui-upload\"> \r\n");
                        sb.Append("      <button type=\"button\" class=\"layui-btn\" id=\"test" + x.EnglishName + "\">上传图片</button> \r\n");
                        sb.Append("      <div class=\"layui-upload-list\">\r\n");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                if (string.IsNullOrWhiteSpace(item[x.EnglishName.ToString()].ToString()))
                                {
                                    sb.Append("        <img src=\"/images/zanwupic.jpg\" class=\"layui-upload-img previewimg\" id=\"demo" + x.EnglishName + "\"> \r\n");
                                    sb.Append("         <input type=\"hidden\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" value=\"\" />\r\n");

                                }
                                else
                                {
                                    sb.Append("        <img src=\"" + item[x.EnglishName.ToString()].ToString() + "\" class=\"layui-upload-img previewimg\" id=\"demo" + x.EnglishName + "\"> \r\n");
                                    sb.Append("         <input type=\"hidden\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" value=\"" + item[x.EnglishName.ToString()].ToString() + "\" />\r\n");

                                }
                            }
                        }
                        else
                        {
                            sb.Append("        <img src=\"/images/zanwupic.jpg\" class=\"layui-upload-img previewimg\" id=\"demo" + x.EnglishName + "\"> \r\n");
                            sb.Append("         <input type=\"hidden\" id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" value=\"\" />\r\n");
                        }
                        sb.Append("         <p id=\"Text" + x.EnglishName + "\"></p> \r\n");
                        sb.Append("      </div> \r\n");
                        sb.Append("    </div> \r\n");
                        sb.Append("   </div> \r\n");
                        sb.Append("</div> \r\n");
                    }
                    #endregion

                    #region 日期控件
                    if (x.FieldType == "date")
                    {
                        datelist.Add(x.EnglishName.ToString());
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("   <label class=\"layui-form-label\">" + x.ChineseName + "</label> \r\n");
                        sb.Append("   <div class=\"layui-input-block\">");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                sb.Append("     <input value=" + DateTime.Parse(item[x.EnglishName.ToString()].ToString()).ToString("yyyy-MM-dd") + " type=\"text\" name=\"" + x.EnglishName + "\" id=\"" + x.EnglishName + "\" lay-verify=\"date\" placeholder=\"yyyy-MM-dd\" autocomplete=\"off\" class=\"layui-input\">\r\n");
                                sb.Append("   </div> \r\n");
                            }
                        }
                        else
                        {
                            sb.Append("     <input type=\"text\" name=\"" + x.EnglishName + "\" id=\"" + x.EnglishName + "\" lay-verify=\"date\" placeholder=\"yyyy-MM-dd\" autocomplete=\"off\" class=\"layui-input\">\r\n");
                            sb.Append("   </div> \r\n");
                        }
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 文本域控件
                    if (x.FieldType == "textarea")
                    {
                        sb.Append("<div class=\"layui-form-item\"> \r\n");
                        sb.Append("   <label class=\"layui-form-label\">" + x.ChineseName + "</label>\r\n");
                        sb.Append("   <div class=\"layui-input-block\">\r\n");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                sb.Append("      <textarea id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" placeholder=\"" + x.Msg + "\" class=\"layui-textarea\">" + item[x.EnglishName.ToString()].ToString() + "</textarea>\r\n");
                                sb.Append("   </div>");
                            }
                        }
                        else
                        {
                            sb.Append("      <textarea id=\"" + x.EnglishName + "\" name=\"" + x.EnglishName + "\" placeholder=\"" + x.Msg + "\" class=\"layui-textarea\"></textarea>\r\n");
                            sb.Append("   </div>");
                        }
                        sb.Append("</div>\r\n");
                    }
                    #endregion

                    #region 编辑框控件
                    if (x.FieldType == "editor")
                    {
                        editordlist.Add(x.EnglishName.ToString());
                        sb.Append("<div class=\"layui-form-item\">\r\n");
                        sb.Append("<label class=\"layui-form-label\">" + x.ChineseName + "</label>\r\n");
                        sb.Append("  <div class=\"layui-input-block\">\r\n");
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                sb.Append("   <textarea class=\"layui-textarea layui-hide editortextarea\" name=\"" + x.EnglishName + "\" lay-verify=\"content\" id=\"" + x.EnglishName + "editor\">" + item[x.EnglishName.ToString()].ToString() + "</textarea>\r\n");
                                sb.Append("</div>\r\n");
                            }
                        }
                        else
                        {
                            sb.Append("   <textarea class=\"layui-textarea layui-hide editortextarea\" name=\"" + x.EnglishName + "\" lay-verify=\"content\" id=\"" + x.EnglishName + "editor\"></textarea>\r\n");
                            sb.Append("</div>\r\n");
                        }
                        sb.Append("</div>\r\n");
                    }
                    #endregion
                }
            });

            #region 提交按钮以及结束
            sb.Append("<div class=\"layui-form-item\">\r\n");
            sb.Append("  <div class=\"layui-input-block\">\r\n");
            sb.Append("    <button class=\"layui-btn\" lay-submit=\"\" lay-filter=\"submitbtn\">立即提交</button>\r\n");
            sb.Append("    <button type=\"reset\" class=\"layui-btn layui-btn-primary\">重置</button>\r\n");
            sb.Append("</div>\r\n");
            sb.Append("</div>\r\n");
            ViewBag.Html = sb.ToString();
            #endregion

            #region js操作部分
            /*js开始拼凑*/
            js.Append("layui.use(['form', 'layedit', 'laydate', 'upload'], function () {\r\n");
            js.Append("          var form = layui.form\r\n");
            js.Append("                      , layer = layui.layer\r\n");
            js.Append("                      , layedit = layui.layedit\r\n");
            js.Append("                      , laydate = layui.laydate\r\n");
            js.Append("                      , upload = layui.upload;\r\n");

            /*日期控件设置*/
            datelist.ForEach(d =>
            {
                js.Append("         laydate.render({\r\n");
                js.Append("         elem: '#" + d + "'\r\n");
                js.Append("         });\r\n");
            });
            /*创建编辑器*/
            editordlist.ForEach(e =>
            {
                js.Append("         var " + e + "editIndex = layedit.build('" + e + "editor');\r\n");
                js.Append("layedit.sync(" + e + "editIndex);");
            });
            /*创建上传控件*/
            uploadlist.ForEach(u =>
            {
                js.Append("         var uploadInst = upload.render({\r\n");
                js.Append("               elem: '#test" + u + "'\r\n");
                js.Append("                , url: '/FormManage/UploadImg'\r\n");
                js.Append("                , data: { fileType: \".jpg\" }");
                js.Append("                , done: function (res) {\r\n");
                js.Append("                     if (res.code > 0) {\r\n");
                js.Append("                         return layer.msg('上传失败');\r\n");
                js.Append("                     }\r\n");
                js.Append("                     else{\r\n");
                js.Append("                             $('#demo" + u + "').attr('src',  res.data.src);\r\n");
                js.Append("                             $('#" + u + "').val( res.data.src);\r\n");
                // js.Append("                             return layer.msg('上传成功'+res.data.src);\r\n");
                js.Append("                     }\r\n");
                js.Append("                }\r\n");
                js.Append("                , error: function () {\r\n");
                js.Append("                          var demoText = $('#Text" + u + "');\r\n");
                js.Append("                          demoText.html('<span style=\"color: #FF5722;\">上传失败</span>');\r\n");
                js.Append("                }\r\n");
                js.Append("         });\r\n");
            });
            js.Append("  form.on('submit(submitbtn)', function (data) { \r\n");
            checkboxlist.ForEach(x =>
            {
                js.Append("         var " + x + "arr = new Array();\r\n");
                js.Append("          $(\"input:checkbox[name='" + x + "']:checked\").each(function(i){\r\n");
                js.Append("               " + x + "arr[i] = $(this).val();\r\n");
                js.Append("          });\r\n");
                js.Append("         data.field." + x + " = " + x + "arr.join(\",\");\r\n");
            });
            js.Append("layer.alert(JSON.stringify(data.field), {title: '最终的提交信息'});\r\n");
            //js.Append("         return false;\r\n");
            js.Append("var index = parent.layer.getFrameIndex(window.name); \r\n");
            js.Append("         $.post(\"/FormManage/FormAction\",{datajson:JSON.stringify(data.field)},\r\n");
            js.Append("             function(data){\r\n");
            //js.Append("                 alert(data.code);\r\n");
            js.Append("                 if(data.code=='100'){");
            js.Append("                 layer.msg(data.msg, {icon: 6},\r\n");
            js.Append("                 function(){\r\n");
            js.Append("                             parent.layer.close(index);");
            js.Append("                             parent.location=document.referrer;\r\n");
            js.Append("                            }\r\n");
            js.Append("                     )\r\n");
            js.Append("                 }\r\n");
            js.Append("                 else{\r\n");
            js.Append("                 layer.msg(data.msg, {icon: 5});\r\n");
            js.Append("                 }\r\n");
            js.Append("         }, \"json\");\r\n");
            js.Append("         return false;\r\n");
            js.Append("  });\r\n");
            js.Append(" });\r\n");
            ViewBag.Js = js.ToString();
            /*js结束拼凑*/
            #endregion
            return View();
        }
        #endregion

        #region 表单提交
        public IActionResult FormAction(string datajson)
        {
            return Json(FormService.EditData(datajson));
        }
        #endregion

        #region 获取表单绑定值
        /// <summary>
        /// 表单绑定值
        /// </summary>
        /// <param name="TableName">表名字</param>
        /// <param name="PkName">查询键</param>
        /// <param name="PkValue">查询键值</param>
        /// <returns>返回表单绑定值</returns>
        public IActionResult GetFormModelData(string TableName, string PkName, string PkValue)
        {
            if (string.IsNullOrWhiteSpace(TableName) || string.IsNullOrWhiteSpace(PkName) || string.IsNullOrWhiteSpace(PkValue))
            {
                return null;
            }
            return Json(FormService.GetArbitrarilyData(TableName, PkName, PkValue));
        }
        #endregion

        #region 获取FieldType
        /// <summary>
        /// 获取FieldType
        /// </summary>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public IActionResult GetTableManageFieldType(string FieldName)
        {
            var model = FormService.GetTableManageField(FieldName).Where(x => x.EnglishName == FieldName).FirstOrDefault();
            return Content(model.FieldType);
        }
        #endregion

        #region 卡片式视图
        public IActionResult CardView(string TableName, string PkName, string PkValue)
        {
            ViewBag.TableName = TableName;
            ViewBag.PkName = PkName;
            ViewBag.PkValue = PkValue;
            if (string.IsNullOrWhiteSpace(TableName) || string.IsNullOrWhiteSpace(PkName) || string.IsNullOrWhiteSpace(PkValue))
            {
                return Content("缺少参数或参数不正确！");
            }
            var list = FormService.GetTableManageFieldList(TableName).OrderBy(x => x.SortOrder).ToList();
            if (list.Count > 0)
            {
                ViewBag.BusinessName = list.FirstOrDefault().BusinessName;
            }
            else
            {
                return Content("关于该参数信息没有配置！");
            }
            DataTable dt = FormService.GetArbitrarilyData(TableName, PkName, PkValue);
            StringBuilder sbhtml = new StringBuilder();
            List<string> checkboxlist = new List<string>();
            string[] bgcolors = new string[5] { "layui-bg-red", "layui-bg-orange", "layui-bg-green", "layui-bg-blue", "" };
            Random ra = new Random();
            if (dt != null)
            {
                var IsTitle = string.Empty;
                var fkname = string.Empty;
                var fkvalue = string.Empty;
                var datalist = string.Empty;
                int sd = dt.Rows.Count;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sbhtml.Append("<div class=\"layui-col-md6 layui-col-sm6\">\r\n");
                    sbhtml.Append(" <div class=\"layui-card " + bgcolors[ra.Next(bgcolors.Length)].ToString() + "\">\r\n");
                    sbhtml.Append("     <div class=\"layui-card-header\">");
                    sbhtml.Append("           <div class=\"layui-row\">\r\n");
                    sbhtml.Append("                   <div class=\"layui-col-md8\">\r\n");

                    list.ForEach(x =>
                    {
                        if (x.IsTitle)
                        {
                            IsTitle = dt.Rows[i][x.EnglishName].ToString();
                            sbhtml.Append("                         " + list.FirstOrDefault().BusinessName + "【" + IsTitle + "】");
                        }
                        if (x.IsFkName)
                        {
                            fkname = x.EnglishName;
                            fkvalue = dt.Rows[i][x.EnglishName].ToString();
                        }
                    });
                    sbhtml.Append("                    </div>\r\n");
                    sbhtml.Append("                     <div class=\"layui-col-md4\">\r\n");
                    sbhtml.Append("                         <button onclick=\"Add()\" class=\"layui- btn layui-btn-primary layui-btn-sm\">新增</button>\r\n");

                    sbhtml.Append("                         <button onclick=\"del('" + fkname + "','" + fkvalue + "')\" class=\"layui- btn layui-btn-primary layui-btn-sm\">删除</button>\r\n");
                    sbhtml.Append("                         <button onclick=\"Update('" + fkname + "','" + fkvalue + "')\" class=\"layui- btn layui-btn-primary layui-btn-sm\">编辑</button>\r\n");
                    sbhtml.Append("                     </div>\r\n");
                    sbhtml.Append("             </div>\r\n");
                    sbhtml.Append("     </div>\r\n");
                    sbhtml.Append("     <div class=\"layui-card-body\">\r\n");
                    sbhtml.Append("         <table class=\"layui-table  " + bgcolors[ra.Next(bgcolors.Length)].ToString() + "\">\r\n");
                    list.ForEach(x =>
                    {
                        if (x.IsSearchPkName)
                        {
                            if (x.FieldType == "radio" || x.FieldType == "select")
                            {
                                DataTable data = FormService.GetControlInfo(x.SqlQuery);
                                sbhtml.Append("             <tr>\r\n");
                                sbhtml.Append("                 <th style=\"text-align:right\">" + x.ChineseName + "</th>\r\n");
                                sbhtml.Append("                 <td>" + data.Rows[0][x.TextFieldName].ToString() + "</td>\r\n");
                                sbhtml.Append("             </tr>\r\n");
                            }
                            if (x.FieldType == "upload")
                            {
                                sbhtml.Append("             <tr>\r\n");
                                sbhtml.Append("                 <th style=\"text-align:right\">" + x.ChineseName + "</th>\r\n");
                                sbhtml.Append("                 <td><img src=\" " + dt.Rows[i][x.EnglishName].ToString() + "\"></td>\r\n");
                                sbhtml.Append("             </tr>\r\n");
                            }
                            else if (x.FieldType == "checkbox")
                            {
                                DataTable data = FormService.GetControlInfo(x.SqlQuery);
                                string[] sArray = null;
                                sbhtml.Append("             <tr>\r\n");
                                sbhtml.Append("                 <th style=\"text-align:right\">" + x.ChineseName + "</th>\r\n");
                                sbhtml.Append("                 <td>");
                                if (data != null && data.Rows.Count > 0)
                                {
                                    sArray = dt.Rows[i][x.EnglishName.ToString()].ToString().Split(',');
                                    if (sArray != null)
                                    {
                                        for (int j = 0; j < data.Rows.Count; j++)
                                        {
                                            bool exists = ((IList)sArray).Contains(data.Rows[j][x.VauleFieldName].ToString());
                                            if (exists)
                                            {
                                                datalist += data.Rows[j][x.TextFieldName].ToString() + ",";
                                            }
                                        }
                                        sbhtml.Append(datalist.TrimEnd(','));
                                    }
                                }

                                sbhtml.Append("<td>\r\n");
                                sbhtml.Append("             </tr>\r\n");
                            }
                            else
                            {
                                sbhtml.Append("             <tr>\r\n");
                                sbhtml.Append("                 <th style=\"text-align:right\">" + x.ChineseName + "</th>\r\n");
                                sbhtml.Append("                 <td>" + dt.Rows[i][x.EnglishName].ToString() + "</td>\r\n");
                                sbhtml.Append("             </tr>\r\n");
                            }
                        }

                    });
                    sbhtml.Append("         </table>\r\n");
                    sbhtml.Append("    </div>\r\n");
                    sbhtml.Append("  </div>\r\n");
                    sbhtml.Append("</div>\r\n");
                }
            }
            ViewBag.CardView = sbhtml.ToString();
            return View();
        }
        #endregion

        #region 图片上传
        public IActionResult UploadImg()
        {
            var ImagePath = Request.Form.Files[0];
            string UploadPath = "/Uploads/Images/" + string.Format("{0:yyyyMMdd}", DateTime.Now) + "/";
            string path = $"{ Directory.GetCurrentDirectory() }/wwwroot" + UploadPath;
            //获取文件后缀名
            string filepath = Path.GetExtension(ImagePath.FileName);
            //判断路径是否存在，不存在则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //判断后缀是否是图片
            const string fileFilt = ".gif|.jpg|.jpeg|.png|.GIF|.JPG|.JPEG|.PNG|";
            if (fileFilt.IndexOf(filepath.ToLower(), StringComparison.Ordinal) <= -1)
            {
                var Result2 = new
                {
                    code = 1 //0表示成功，其它失败
                             ,
                    msg = "请上传图片格式文件：.gif|.jpg|.jpeg|.png|.GIF|.JPG|.JPEG|.PNG|" //提示信息 //一般上传失败后返回
                   ,
                    data = new
                    {
                        src = ""
                    ,
                        title = "失败！" //可选
                    }
                };
                return Json(Result2);
            }
            //创建文件名
            var fileName = CreateMd5(Guid.NewGuid().ToString()) + filepath;
            using (FileStream fs = System.IO.File.Create(path + fileName, 320))
            {
                ImagePath.CopyTo(fs);
                fs.Flush();
            }
            var Result = new
            {
                code = 0 //0表示成功，其它失败
                    ,
                msg = "上传成功" //提示信息 //一般上传失败后返回
                    ,
                data = new
                {
                    src = UploadPath + fileName
                        ,
                    title = fileName //可选
                }
            };
            return Json(Result);
        }

        public static string CreateMd5(string inputValue)
        {
            //32位大写
            using (var md5 = MD5.Create())
            {
                var data = md5.ComputeHash(Encoding.UTF8.GetBytes(inputValue));
                StringBuilder builder = new StringBuilder();
                // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 
                for (int i = 0; i < data.Length; i++)
                {
                    builder.Append(data[i].ToString());
                }
                return builder.ToString();
            }
        }
        #endregion

    }
}